import usocket
import time
import _thread
import ujson

server = None
clientsocket = None
client_addr = None

def mesg_calback(client_socket,data):
    try:
        print(data.decode())
        client_socket.send("receive".encode('utf-8'))
        data = ujson.loads(data.decode())
        wifiname = data["wifiname"]
        wifipassword = data["wifipassword"]
        # print(wifiname)
        # print(wifipassword)
        #保存为json文件
        wifi_config = {"wifiname": wifiname, "wifipassword": wifipassword}
        f=open("/wificonfig.json","w")
        wifi_json = ujson.dumps(wifi_config)  #转json字符
        f.write(wifi_json)
        f.flush()
        f.close()
    except Exception as e:
        print("mesg_calback err")

def handle_client(client_socket,address):
    print("连接成功:"+ str(address))
    while True:
        try:
            data = client_socket.recv(1024)
            mesg_calback(client_socket,data)
        except Exception as e:
             print("连接断开。。。")
             break

#读取信息
def read_message():
    data = clientsocket.recv(1024)


#等待客户端连接
def check_connect():
    global clientsocket,client_addr 
    while True:
        age = input("input:\n")
        if age.find("lh") != -1:
            print(age)

    # clientsocket, client_addr = server.accept()
    # print("connect address: %s" % str(client_addr))
    


#创建tcp服务端
def creat_tcp_server():
    # Create STREAM TCP socket
    global server
    server = usocket.socket(usocket.AF_INET, usocket.SOCK_STREAM)
    server.bind(('192.168.5.0', 6666))
    server.listen(5)
    server.setblocking(True)
    _thread.start_new_thread(check_connect,())
        